package com.liu.manag.controller;

import com.liu.manag.entity.Todo;
import com.liu.manag.entity.User;
import com.liu.manag.enums.StatusEnum;
import com.liu.manag.enums.TypeEnum;
import com.liu.manag.security.UserAuthenticationExtractor;
import com.liu.manag.service.TodoService;
import com.liu.manag.utils.CSVUtil;
import com.liu.manag.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Principal;
import java.util.*;

/**
 * (Todo)表控制层
 *
 * @author liu
 * @since 2020-03-11 10:09:10
 */
@RestController
@RequestMapping("/todo")
@Slf4j
public class TodoController {
    /**
     * 服务对象
     */
    @Resource
    private TodoService todoService;

    @GetMapping("")
    public Result<List<Todo>> getTodo(@RequestParam("status") int status,
                                      @RequestParam(value = "page", required = false) Integer _page,
                                      @RequestParam(value = "size", required = false) Integer _size,
                                      Principal principal) {
        int page = Objects.nonNull(_page) ? _page - 1 : 0;
        int size = Objects.nonNull(_size) ? _size : 10;
        User operator = UserAuthenticationExtractor.extract(principal);
        List<Todo> todos = todoService.queryByStatus(operator.getId(), status, page, size);

        return new Result<>(todos);
    }

    @PostMapping("")
    public Result<String> addTodo(@RequestParam("date") Date date,
                                  @RequestParam("type") int type,
                                  @RequestParam("name") String name,
                                  @RequestParam("describe") String describe,
                                  @RequestParam("begin") int begin,
                                  @RequestParam("end") int end,
                                  Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);
        todoService.insert(operator.getId(), date, type, name, describe, begin, end);
        return new Result<>("新增成功");
    }

    public Result<String> updateTodo(@RequestParam("date") Date date,
                                     @RequestParam("todoId") Long todoId,
                                     @RequestParam("describe") String describe,
                                     @RequestParam("status") int status,
                                     @RequestParam("begin") int begin,
                                     @RequestParam("end") int end,
                                     Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);

        todoService.update(operator.getId(), todoId, date, status, describe, begin, end);

        return new Result<>("更新成功");

    }

    public Result<String> deleteTodo(@RequestParam("id") Long id,
                                     Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);
        Boolean state = todoService.deleteById(operator.getId(), id);
        if (state) {
            return new Result<>("删除成功");
        }
        return new Result<>(500, 500, "删除失败");

    }

    public Result<String> export(HttpServletResponse response,
                                 @RequestParam(value = "ids", required = false) Long[] ids,
                                 Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);
        List<Todo> todoList = todoService.queryByUserIdAndIds(operator.getId(), ids);
        if (CollectionUtils.isEmpty(todoList)) {
            return new Result<>("无数据导出");
        }
        String titles = "日期,任务名,类型,描述,开始时间,结束时间";
        String keys = "date,name,type,describe,begin,end";

        //构造导出数据
        List<Map<String, Object>> datas = new ArrayList<>();
        Map<String, Object> map = null;
        for (Todo todo : todoList) {
            map = new HashMap<>();
            map.put("id", todo.getId());
            map.put("name", todo.getName());
            map.put("date", todo.getDate());
            map.put("describe", todo.getDescribe());
            map.put("type", TypeEnum.getValueByKey(todo.getType()));
            map.put("begin", todo.getBegin());
            map.put("end", todo.getEnd());
            map.put("status", StatusEnum.getValueByKey(todo.getState()));

            datas.add(map);

        }
        String fName = "待办事项";
        try {
            OutputStream os = response.getOutputStream();
            CSVUtil.responseSetProperties(fName, response);
            CSVUtil.doExport(datas, titles, keys, os);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导出失败");
        }


        return new Result<>("导出成功");
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public Todo selectOne(Long id) {
        return this.todoService.queryById(id);
    }


}